var VIEW = VIEW || {};

VIEW.submit = VIEW.submit ||
(function () {
	var submitTimer = function () {
		var timer = null;

		var isComplete = function () {
			return (typeof document.readyState === "undefined" || document.readyState === "complete");
		};

		return {
			isSubmitting: function () {
				return (timer !== null);
			},
			canSubmit: function () {
				return (!this.isSubmitting() || isComplete());
			},
			setSubmitTimer: function (msec) {
				var mmm = 3000;
				if (msec && !isNaN(msec)) {
					mmm = msec;
				}
				timer = window.setInterval(VIEW.submit.reset, mmm);
			},
			resetSubmitTimer: function () {
				if (isComplete()) {
					window.clearInterval(timer);
					timer = null;
				}
			}
		};
	}();

	var request = function (method, fm, aid, action, target) {
		var m = null;
		if (method) {
			m = fm.method;
			fm.method = method;
		}
		var a = null;
		if (action) {
			a = fm.action;
			fm.action = action;
		}
		var t = null;
		if (target) {
			t = fm.target;
			fm.target = target;
		} else {
			t = fm.target;
			fm.target = "_self";
		}

		setAid(fm, aid);
		fm.submit();

		if (m) {
			fm.method = m;
		}
		if (a) {
			fm.action = a;
		}
		if (t) {
			fm.target = t;
		}
	};

	var setAid = function(fm, aid) {
		if (aid) {
			var ele = null;
			var nodes = fm.childNodes;
			for (var i = 0, len = nodes.length; i < len; i += 1) {
				if (nodes[i].name === "AID") {
					ele = nodes[i];
					break;
				}
			}
			if (!ele) {
				ele = document.createElement("input");
				ele.setAttribute("id", "aid");
				ele.setAttribute("name", "AID");
				ele.setAttribute("type", "hidden");
				fm.appendChild(ele);
			}
			ele.value = aid;
		}
	};

	return {
		set: function() {
			if (submitTimer.canSubmit()) {
				submitTimer.setSubmitTimer();
				return true;
			}
			return false;
		},
		reset: function() {
			submitTimer.resetSubmitTimer();
		},
		get: function (formId, action, target) {
			if (formId && submitTimer.canSubmit()) {
				submitTimer.setSubmitTimer();
				request("get", document.getElementById(formId), null, action, target);
			}
		},
		post: function (formId, aid, action, target) {
			if (formId && submitTimer.canSubmit()) {
				submitTimer.setSubmitTimer();
				request("post", document.getElementById(formId), aid, action, target);
			}
		},
		relocate: function (action) {
			if (action && !submitTimer.isSubmitting()) {
				submitTimer.setSubmitTimer();
				window.location.href = action;
			}
		}
	};
}());
